package com.dns.customers.service.impl;

import com.dns.customers.dao.ExportDao;
import com.dns.customers.service.ExportService;
import com.dns.framework.page.Pagination;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.util.XlsMain;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.OutputStream;
import java.util.*;
import java.util.List;

/**
 * @author :  yulei
 * @data :  2018/7/27 14:11
 * @Version :  1.0
 **/

@Service
@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class)
public class ExportServiceImpl implements ExportService {


    @Autowired
    ExportDao exportDao;
    /**
     * 导出订单明细
     * @param document
     * @param request
     * @throws Exception
     */
    public void exportOrderDetailPdf(Document document, HttpServletRequest request) throws Exception {

        //设置字体
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font FontChinese18 = new Font(bfChinese, 18, com.itextpdf.text.Font.BOLD);
        Font FontChinese11Bold = new Font(bfChinese, 11, com.itextpdf.text.Font.BOLD);
        BaseColor lightGrey01 = new BaseColor(0xCC,0xCC,0xCC);

        BaseColor lightGrey02 = new BaseColor(0xCC,0xCC,0xCC);

        document.open();
        //主题文字
        Paragraph pg_bt = new Paragraph("DNS订单明细报表", FontChinese18);
        pg_bt.setAlignment(Element.ALIGN_CENTER);
        document.add(pg_bt);
        PdfPTable table = new PdfPTable(3);
        String[] title ={"域名","解析类型","解析结果","执行时间","更新时间","地市","省份"};
        //添加表格标题
        for(String str:title){
            PdfPCell titleCell = new PdfPCell();
            //水平居中
            titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
            //垂直九中
            titleCell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
            //边框颜色
            titleCell.setBorderColor(lightGrey01);
            table.addCell(titleCell);
        }
        //将数据库取出的内容添加到PDF文件当中
        String orderId= request.getParameter("ORDER_ID");
        Pagination pagination =new Pagination();
        pagination.setCurrPage(1);
        pagination.setPageSize(5);
        //    IDataset dataset =  domainDao.getExportOrderDetailList(orderId,pagination);

        document.add(table);
    }

    @Override
    public void exportOrderDetailByExcel(HttpServletRequest request, OutputStream out) throws Exception  {
        //订单ID
        String orderId= request.getParameter("ORDER_ID");
        //任务类型 0:域名解析，1:缓存清除
        String taskType=request.getParameter("TASK_TYPE");
        //文件名后缀时.xlsx
        HSSFWorkbook wb = new HSSFWorkbook();

        //文件名称
        String sheetName="";
        //DNS解析表头
        String[] headers_resolve={"","订单编号","域名名称","DNS解析类型","DNS解析结果","执行时间","更新时间","地市","省份"};
        //DNS 缓存清除表头
        String[] headers_clean = {"","订单编号","域名名称","DNS缓存清除结果","更新时间","省份"};

        //excel 表头
        String[] headers={};
        if("0".equals(taskType)){
            sheetName="域名解析明细报表";
            headers=headers_resolve;
        }else if("1".equals(taskType)){
            sheetName="域名缓存清除明细报表";
            headers=headers_clean;
        }else{
            //类型错误，直接抛出异常
            throw new RuntimeException("错误的任务类型:"+taskType);
        }

        HSSFSheet sheet  = wb.createSheet(sheetName);
        //设置表格默认列宽度为20个字节
        sheet.setColumnWidth(0,10*256);
        sheet.setColumnWidth(1,20*256);
        sheet.setColumnWidth(2,20*256);
        sheet.setColumnWidth(3,20*256);
        //域名解析结果特殊处理
        if("0".equals(taskType)){
            sheet.setColumnWidth(4,50*256);
        } else{
            sheet.setColumnWidth(4,20*256);

        }
        sheet.setColumnWidth(5,20*256);
        sheet.setColumnWidth(6,20*256);
        sheet.setColumnWidth(7,20*256);
        sheet.setColumnWidth(8,20*256);

        //表头样式
        HSSFCellStyle style_header= wb.createCellStyle();
        style_header.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style_header.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style_header.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style_header.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style_header.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //生成一个字体
        HSSFFont font_header = wb.createFont();
        font_header.setFontHeightInPoints((short) 10);
        font_header.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //将字体应用与当前样式
        style_header.setFont(font_header);

        // 生成一个样式
        HSSFCellStyle style_body = wb.createCellStyle();
        style_body.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style_body.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style_body.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style_body.setBorderTop(HSSFCellStyle.BORDER_THIN);
        //自动换行
        style_body.setWrapText(true);
        // 设置这些样式
        // 生成一个字体
        HSSFFont font_body = wb.createFont();
        font_body.setFontHeightInPoints((short) 10);
        font_body.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        style_body.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 把字体应用到当前的样式
        style_body.setFont(font_body);

        //若是域名解析，则查询域名解析结果
        List<Map<String,Object>> result= exportDao.queryOrderDetailByOrderId(orderId);

        //设置表头
        HSSFRow row =sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell =row.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(style_header);
        }
        //输出表体，分两种情况：域名解析、域名缓存清除
        int r=1;
        if("0".equals(taskType)){
            for(Map<String,Object> map :result){
                row =sheet.createRow(r);
                HSSFCell seqCell    =row.createCell(0);
                HSSFCell orderCell  =row.createCell(1);
                HSSFCell domainCell =row.createCell(2);
                HSSFCell typeCell   =row.createCell(3);
                HSSFCell resCell    =row.createCell(4);
                HSSFCell excCell    =row.createCell(5);
                HSSFCell uptCell    =row.createCell(6);
                HSSFCell areaCell   =row.createCell(7);
                HSSFCell proCell    =row.createCell(8);
                //序列号
                seqCell.setCellValue(r);
                orderCell.setCellValue((String) map.get("ORDER_ID"));
                domainCell.setCellValue((String) map.get("DOMAIN_NAME"));
                typeCell.setCellValue((String) map.get("TYPE"));
                resCell.setCellValue((String) map.get("RES"));
                excCell.setCellValue((String) map.get("EXECU_TIME"));
                uptCell.setCellValue((String) map.get("UPDATE_TIME"));
                areaCell.setCellValue((String) map.get("AREA_NAME"));
                proCell.setCellValue((String) map.get("PROVINCE_NAME"));

                seqCell.setCellStyle(style_body);
                orderCell.setCellStyle(style_body);
                domainCell.setCellStyle(style_body);
                typeCell.setCellStyle(style_body);
                resCell.setCellStyle(style_body);
                excCell.setCellStyle(style_body);
                uptCell.setCellStyle(style_body);
                areaCell.setCellStyle(style_body);
                proCell.setCellStyle(style_body);
                //行数计数器
                r++;
            }
        }

        else{
            for(Map<String,Object> map :result) {
                row = sheet.createRow(r);
                HSSFCell seqCell = row.createCell(0);
                HSSFCell orderCell = row.createCell(1);
                HSSFCell domainCell = row.createCell(2);
                HSSFCell resCell = row.createCell(3);
                HSSFCell uptCell = row.createCell(4);
                HSSFCell proCell = row.createCell(5);
                //序列号
                seqCell.setCellValue(r);
                orderCell.setCellValue((String) map.get("ORDER_ID"));
                domainCell.setCellValue((String) map.get("DOMAIN_NAME"));
                resCell.setCellValue((String) map.get("RES"));
                uptCell.setCellValue((String) map.get("UPDATE_TIME"));
                proCell.setCellValue((String) map.get("PROVINCE_NAME"));

                seqCell.setCellStyle(style_body);
                orderCell.setCellStyle(style_body);
                domainCell.setCellStyle(style_body);
                resCell.setCellStyle(style_body);
                uptCell.setCellStyle(style_body);
                proCell.setCellStyle(style_body);
                r++;
            }
        }

        wb.write(out);
    }
    /**
     * 批量导入根域名信息（回显）
     * @param file
     * @return
     */
    public String importRootDomains(MultipartFile file){
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            if (file == null || file.isEmpty()) {
                message.put("reusultcode", "导入的文件为空!");
                message.put("message", "导入的文件为空!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            List<List<Map<String,Object>>> list = XlsMain.readXls(file);
            if (list == null){
                message.put("reusultcode", "文件格式不正确!");
                message.put("message", "文件格式不正确!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            List result = new ArrayList();
            for (List<Map<String,Object>> rowList : list){
                for (Map<String,Object> map : rowList){
//                    if (map.get("domainType"))
                    String domainName = (String) map.get("domainName");
                    if (domainName == null){
                        continue;
                    }
//                    //验证域名名称的格式是否满足 *.*.* 格式，只要有不满足的，就提示错误
//                    String patten = "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+";
//                    if (!domainName.matches(patten)){
//                        continue;
//                    }
                    String num = ((String) map.get("domainType")).trim();
                    if (num == null || "".equals(num) || Double.parseDouble(num) != 0){
                        continue;
                    }
                    result.add(map);
                }
            }
            message.put("message", "解析成功!");
            resultJson.put("result", result);
        }catch (Exception e){
            message.put("reusultcode", e);
            message.put("message", "文件格式不正确");
            resultJson.put("result", message);
            e.printStackTrace();
        }
        return resultJson.toString();
    }
    /**
     * 批量导入子域名信息（回显）
     * @param file
     * @return
     */
    public String importChildDomains(MultipartFile file,String custId){
        JSONObject resultJson = new JSONObject();
        JSONObject message = new JSONObject();
        try {
            if (file == null || file.isEmpty()) {
                message.put("reusultcode", "1111");
                message.put("message", "导入的文件为空!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            List<List<Map<String,Object>>> list = XlsMain.readXls(file);
            if (list == null){
                message.put("reusultcode", "1111");
                message.put("message", "文件格式不正确!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            String patten = "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+";
            //查询这个账户下的根域名
            if (custId == null){
                message.put("reusultcode", "1111");
                message.put("message", "找不到这个客户!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            List<String> rootDomainList = exportDao.queruRootDomainByCustId(custId);
            if (rootDomainList == null){
                message.put("reusultcode", "1111");
                message.put("message", "没有找到客户的根域名信息!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            String msg = "";
            //做一个锁
            boolean b = true;
            List<String> resultList = new ArrayList<>();
            Map<String,String> resultMap = new HashMap<>();
            for (List<Map<String,Object>> rowList : list){
                for (Map<String,Object> map : rowList){
                    String domainName = (String) map.get("domainName");
                    if (domainName == null){
                        continue;
                    }
//                    //验证域名名称的格式是否满足 *.*.* 格式，只要有不满足的，就提示错误
//                    if (!domainName.matches(patten)){
//                        b = false;
//                        msg += domainName+"格式不正确; ";
//                    }
                    //验证域名的根域名是否存在
                    boolean  rb = false;
                    for (String name : rootDomainList){
                        if (domainName.contains(name)){
                            rb = true;
                            break;
                        }
                    }
                    if (rb){
                        resultMap.put(domainName,"0");
                    }else{
                        b = false;
                        msg += domainName+"的根域名不存在 ";
                    }
                }
            }
            if(b){
                resultList.addAll(resultMap.keySet());
                message.put("message", "解析成功!");
                message.put("data",resultList);
                resultJson.put("result", message);
            }else {
                message.put("reusultcode", "1111");
                message.put("message", msg);
                resultJson.put("result", message);
            }
        }catch (Exception e){
            message.put("reusultcode", e);
            message.put("message", "文件解析异常");
            resultJson.put("result", message);
            e.printStackTrace();
        }
        return resultJson.toString();
    }
    /**
     * 验证下发任务时的子域名是否正确
     * @param custId
     * @param domainName
     * @return
     */
    public String checkDomainFormat(String custId,String domainName){
        JSONObject message = new JSONObject();
        JSONObject resultJson = new JSONObject();
        try{
            if (domainName == null || "".equals(domainName)){
                message.put("errorCode", "1111");
                message.put("message", "请传入域名!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            List<String> rootDomainList = exportDao.queruRootDomainByCustId(custId);
            if (rootDomainList == null){
                message.put("errorCode", "1111");
                message.put("message", "没有找到客户的根域名信息!");
                resultJson.put("result", message);
                return resultJson.toString();
            }
            boolean b = false;
            for (String name : rootDomainList){
                if (domainName.contains(name)){
                    b = true;
                    break;
                }
            }
            if (b){
                message.put("message","域名正确");
                resultJson.put("result",message);
            }else{
                message.put("message","没有这个根域名");
                message.put("errorCode","1111");
                resultJson.put("result",message);
            }
        }catch (Exception e){
            message.put("message","查询结果异常");
            message.put("errorCode","查询结果异常:"+e);
            resultJson.put("result",message);
        }
        return resultJson.toString();
    }
    public static void main(String[] args) {
        System.out.println("请输入字符：");
        Scanner scan = new Scanner(System.in);
        String putten = "\\d+\\.\\d+\\.\\d+\\.\\d+";
        String ss = scan.nextLine();
        System.out.println(putten.matches(ss));
    }
}
